import * as XLSX from 'xlsx'
import settings from '../utils/setting'
export default {
    aryVal(ary, status) {
        return settings.globalData[ary].find(t => t.status == status.toString()).text
    },
    dateFormat(d,fmt) {
        var o = { 
            "M+" : d.getMonth()+1,                 //月份 
            "d+" : d.getDate(),                    //日 
            "h+" : d.getHours(),                   //小时 
            "m+" : d.getMinutes(),                 //分 
            "s+" : d.getSeconds(),                 //秒 
            "q+" : Math.floor((d.getMonth()+3)/3), //季度 
            "S" : d.getMilliseconds()             //毫秒 
        }; 
        if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (d.getFullYear()+"").substr(4 - RegExp.$1.length)); 
        }
        for(var k in o) {
            if(new RegExp("("+ k +")").test(fmt)){
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
            }
        }
        return fmt;
    },
    dateAddMinute(d,minute,fmt){
        let nd = new Date(d.getTime()+minute*60*1000);
        if(fmt)
            return this.dateFormat(nd, fmt)
        return nd
    },
    dateAddHour(d,hour,fmt){
        let nd = new Date(d.getTime()+hour*60*60*1000);
        if(fmt)
            return this.dateFormat(nd, fmt)
        return nd
    },
    dateAddDay(d,day,fmt){
        let nd = new Date(d.getTime()+day*24*60*60*1000)
        if(fmt)
            return this.dateFormat(nd, fmt)
        return nd
    },
    dateAddMonth(d,month,fmt){

    },
    dateAddYear(d,year,fmt){

    },
    removeHTML(str, len){
        str = str.replace(/<[^>]+>/g,' ');
        if(len){
            if(str.length > len){
                str = str.substr(0,len) + "...";
            }
        } 
        return str;
    },
    convertSize(l) {
        if(l<1024)
            return l + "B";
        if (l<1024*1024)
            return (l/1024.0).toFixed(1) + "KB";
        if (l<1024*1024*1024)
            return (l/1024/1024.0).toFixed(1) + "MB";
    },
    position(point, params, dom, rect, size) {
		var x = 0; // x坐标位置
		var y = 0; // y坐标位置
		// 当前鼠标位置
		var pointX = point[0];
		var pointY = point[1];
	
		// 提示框大小
		var boxWidth = size.contentSize[0];
		var boxHeight = size.contentSize[1];
	
		// boxWidth > pointX 说明鼠标左边放不下提示框
		if (boxWidth > pointX) {
			x = 5;
		} else { // 左边放的下
			x = pointX - boxWidth;
		}
	
		// boxHeight > pointY 说明鼠标上边放不下提示框
		if (boxHeight > pointY) {
			y = 5;
		} else { // 上边放得下
			y = pointY - boxHeight;
		}
	
		return [x, y];
	},
    // 判断某元素是否有滚动条 id
    hasScrolled(id, direction = "vertical") {
        let el = document.getElementById(id)
        if(direction === "vertical") {
            return el.scrollHeight > el.clientHeight;
        }else if(direction === "horizontal") {
            return el.scrollWidth > el.clientWidth;
        }
    },
    ExcelExport(dataList, fields, headers, fileName = 'Excel.xlsx', sheetName = 'Sheet', ref, merge = [], isDown = true) {
        let fileNamexlsx = `${fileName}.xlsx`
        return new Promise((resolve, reject) => {
        let data = new Array()
        if (!Array.isArray(dataList)) return console.warn('dataList is not an array type')
        // if (!Array.isArray(fields)) return console.warn('fields is not an array type')
        // if (!Array.isArray(headers)) return console.warn('headers is not an array type')

        data = dataList.map((obj) => {
            return fields.map((field) => {
            return obj[field]
            })
        })
        if (headers.length > 0) {
            data.splice(0, 0, headers)
        } else {
            // 将headers设置为英文字段表头
            data.splice(0, 0, fields)
        }
        // console.log('data',data);
        // return
        const ws = XLSX.utils.aoa_to_sheet(data) // 创建工作表
        const wb = XLSX.utils.book_new() // 创建工作簿

        if (ref && merge.length) {
            // 设置工作表的记录范围
            // [列号][行号]，A1 则代表 A 列的第1行
            // 列数一般是已知的（未知时可以设置为ZZ）
            // 行数则以 data 内容的长度结束即可
            // ws['!ref'] = `A1:N${data.length}`;
            ws['!ref'] = ref;
            // s 意为 start ，即开始的单元格
            // r 是 row ，表示行号，从 0 计起
            // c 是 col ，表示列号，从 0 计起
            // 示例
            // const merge = [
            //   // 纵向合并，范围是第1列的行1到行2
            //   { s: { r: 0, c: 0 }, e: { r: 1, c: 0 } },
            // ]
            ws['!merges'] = merge;
        }

        XLSX.utils.book_append_sheet(wb, ws, sheetName) // 将工作表添加到工作簿中
        if (isDown) {
            XLSX.writeFile(wb, fileNamexlsx) // 导出文件
        } else {
            let sheet2blob = (sheet, sheetName) => {
            let workbook = {
                SheetNames: [sheetName],
                Sheets: {}
            };
            workbook.Sheets[sheetName] = sheet;
            // 生成excel的配置项
            let wopts = {
                bookType: 'xlsx', // 要生成的文件类型
                bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
                type: 'binary'
            };
            let wbout = XLSX.write(workbook, wopts);
            // 字符串转ArrayBuffer
            let s2ab = (s) => {
                var buf = new ArrayBuffer(s.length);
                var view = new Uint8Array(buf);
                for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
                return buf;
            }
            var blob = new Blob([s2ab(wbout)], { type: "application/octet-stream" });
            return blob;
            }
            const blobData = sheet2blob(ws, fileName)
            resolve(blobData)
        }
        })
    },
}